const request = require('superagent');
require('superagent-proxy')(request);
module.exports = {
    // 模块介绍
    summary: 'my customized rule for AnyProxy',
    // 发送请求前拦截处理
    async beforeSendRequest(requestDetail) {
        try{
            let host = requestDetail.requestOptions.hostname.match(/(\S+\.)*(\S+)\.(com|cn)/)[2];
            let url = `${requestDetail.protocol}://${requestDetail.requestOptions.hostname}${requestDetail.requestOptions.path}`;
            let cacheUrl = requestDetail.requestOptions.headers.Referer || url;
            let proxyInfo = await sesame.getProxyIP(host, url, cacheUrl);
            let isResource = false;
            if(requestDetail.requestOptions.hostname === "dis.tianyancha.com" || requestDetail.requestOptions.path.match(/(stock|discuss|\.js$|\.ico|\.png|\.css|\.gif|\.jpg|\.ttf|getJsSdkConfig\.json|v\.js|hm\.js|\.woff|getCaptcha\.json|doctor\.json|@!fill)/)) isResource = true;
            if(!isResource) {
                if(requestDetail.requestOptions.method === "GET"){
                    try{
                        let response = await request("GET",url).set(requestDetail.requestOptions.headers)
                            .proxy(`http://${proxyInfo.ip}:${proxyInfo.port}`).timeout(30*1000);
                        delete response.headers['content-encoding'];
                        if(proxyInfo.use === 1)await sesame.raiseIpCount(proxyInfo.tel);
                        return {
                            response: {
                                statusCode: response.statusCode,
                                header: response.headers,
                                body: response.text
                            }
                        };
                    } catch(e){
                        if(e.response){
                            if(proxyInfo.use === 1)await sesame.raiseIpCount(proxyInfo.tel);
                            return {
                                response: {
                                    statusCode: e.response.statusCode,
                                    header: e.response.headers,
                                    body: e.response.text
                                }
                            };
                        } else {
                            if(proxyInfo) console.error('proxy GET', url, `http://${proxyInfo.ip}:${proxyInfo.port}`, e.message);
                            if(e.message.indexOf("connect ETIMEDOUT") >= 0) await sesame.removeIP(proxyInfo.ip, proxyInfo.port);
                            return null;
                        }
                    }
                } else if(requestDetail.requestOptions.method === "POST" ) {
                    let type = null, data = {};
                    try{
                        switch(requestDetail.requestOptions.headers["Content-Type"]){
                            case "application/x-www-form-urlencoded; charset=UTF-8":
                            case "application/x-www-form-urlencoded":
                                type = 'form';
                                let str = requestDetail.requestData.toString();
                                let array = str.split("&");
                                for(let kv of array){
                                    let obj = kv.split("=");
                                    let k = obj.splice(0,1);
                                    data[k[0]] = obj.join("=");
                                }
                                break;
                            case "application/json; charset=UTF-8":
                            case "application/json":
                                type = 'json';
                                data = JSON.parse(requestDetail.requestData.toString());
                                break;
                        }
                        if(type){
                            let response = await request("POST",url).set(requestDetail.requestOptions.headers).type(type).send(data)
                                .proxy(`http://${proxyInfo.ip}:${proxyInfo.port}`).timeout(30*1000);
                            delete response.headers['content-encoding'];
                            if(proxyInfo.use === 1)await sesame.raiseIpCount(proxyInfo.tel);
                            return {
                                response: {
                                    statusCode: response.statusCode,
                                    header: response.headers,
                                    body: response.text
                                }
                            };
                        } else {
                            return null;
                        }
                    } catch(e){
                        if(e.response){
                            if(proxyInfo.use === 1)await sesame.raiseIpCount(proxyInfo.tel);
                            return {
                                response: {
                                    statusCode: e.response.statusCode,
                                    header: e.response.headers,
                                    body: e.response.text
                                }
                            };
                        } else {
                            if(e.message.indexOf("connect ETIMEDOUT") >= 0) await sesame.removeIP(proxyInfo.ip, proxyInfo.port);
                            if(proxyInfo) console.error('proxy post', url, `http://${proxyInfo.ip}:${proxyInfo.port}`, e.message, type, requestDetail.requestOptions.headers);
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }catch(e){
            console.error(e)
        }
    },
    // 发送响应前处理
    *beforeSendResponse(requestDetail, responseDetail) {},
    // 是否处理https请求
    *beforeDealHttpsRequest(requestDetail) { return true },
    // 请求出错的事件
    *onError(requestDetail, error) {
        console.error("onError", error);
        return {
            response: {
                statusCode: 200,
                header: { 'content-type': 'text/html' },
                body: '请求出错'
            }
        };
    },
    // https连接服务器出错
    *onConnectError(requestDetail, error) {
        console.error("onConnectError", error);
        return {
            response: {
                statusCode: 200,
                header: { 'content-type': 'text/html' },
                body: '请求出错'
            }
        };
    }
};